<template>
  <div class="dispatch-equ-sort-container">
    <div class="content-root">
      <equ-list
        @select-eq-change="selectEqChange"
        @select-wc-change="selectWcChange"
      />
      <div class="info-content">
        <div class="info-content-top">
          <searchParam
            @refresh-data="refreshData"
            @save-data="saveData"
            @search-param-callback="searchParamCallback"
          />
          <div v-infinite-scroll="loadData" class="drag-content">
            <draggable
              class="list-group"
              :draggable="false"
              group="dispatchList"
              item-key="pkDispatchH"
              :list="state.unDispatchList"
              :move="unmove"
              @change="unDispatchChange"
            >
              <template #item="{ element }">
                <el-col :lg="4" :md="4" :sm="6" :xl="4" :xs="8">
                  <div style="margin: 6px">
                    <div class="dispatch-item">

                      <div :class="['jb-scddh',element.type==2?'jb-scddh-fangong':'',]">
                        {{ element.scddh }}&nbsp;
                      </div>
                      <div class="opt-tag">
                        {{ element.opName }}
                      </div>
                      <div class="item-filed">
                        <div
                          class="filed-name"
                          style="
                            min-height: 32px;
                            font-size: 12px;
                            word-break: break-all;
                          "
                        >
                          {{ element.invname }}
                        </div>
                        <div
                          class="item-filed-content"
                          style="
                            min-height: 32px;
                            font-size: 12px;
                            word-break: break-all;
                          "
                        >
                          <!-- <div class="filed-placeholder">编码</div> -->
                          {{ element.invcode }}
                        </div>
                        <div
                          class="item-filed-content"
                          style="box-shadow: none"
                        >
                          <!-- <div class="filed-placeholder">规格</div> -->
                          {{ element.invtype }}&nbsp;
                        </div>
                      </div>
                      <!-- <div class="item-filed" style="flex: 2">
                        <div
                          class="item-filed-content"
                          style="box-shadow: none"
                        >
                          <div class="filed-placeholder">工序</div>
                          {{ element.opName }}&nbsp;
                        </div>
                      </div> -->
                      <!-- <div style="display: flex">
                        <div style="flex: 1">
                          <div>{{ element.opName }}&nbsp;</div>
                          <div>{{ element.measName }}</div>
                        </div>
                        <div style="flex: 1"></div>
                      </div> -->
                      <!-- <div style="flex: 3"> -->
                      <!-- <div class="filed-number">数量</div> -->
                      <div style="display: flex; line-height: 24px">
                        <span style="font-size: 12px; color: #4793ff">
                          数量
                        </span>
                        <el-input-number
                          v-model="element.mQty"
                          :controls="false"
                          :min="0"
                          size="small"
                          :step="1"
                          style="flex: 1; margin: 0 3px"
                        />
                        {{ element.measName }}
                      </div>
                      <div class="item-filed-content">
                        <!-- <div class="filed-placeholder">型号</div> -->
                        {{ element.invspec }}
                      </div>
                    </div>
                    <!-- </div> -->
                  </div>
                </el-col>
              </template>
            </draggable>
          </div>
        </div>
        <dispatchMiddle
          ref="dispatchMiddleRef"
          :can-change-date-time="canChangeDateTime"
          @select-date-time-callback="selectDateTimeCallback"
        />
        <div class="info-content-bottom">
          <draggable
            class="list-group"
            group="dispatchList"
            item-key="pkDispatchH"
            :list="state.dispatchedList"
            @change="dispatchedChange"
            @move="move"
          >
            <template #item="{ element }">
              <el-col :lg="4" :md="4" :sm="6" :xl="4" :xs="8">
                <div v-if="element.pkMoldDoc" style="margin: 6px">
                  <el-popover placement="top" trigger="click" :width="1000">
                    <template #reference>
                      <div class="dispatch-item">
                        <div
                          :class="[
                            'jb-scddh',
                            element.pkDispatchMid ? '' : 'jb-scddh-undispatch',
                          ]"
                        >
                          模具
                          {{ itemChildrenCount(element) }}/{{
                            element?.cavityList?.length || 0
                          }}
                          <el-icon
                            style="position: absolute; top: 2px; right: 6px"
                          >
                            <InfoFilled />
                          </el-icon>
                        </div>

                        <div class="item-filed">
                          <div class="filed-name">
                            {{ element.moldName }}&nbsp;
                          </div>
                          <div class="item-filed-content">
                            <div class="filed-placeholder">模具编码</div>
                            {{ element.moldCode }}&nbsp;
                          </div>
                          <div
                            class="item-filed-content"
                            style="box-shadow: none"
                          >
                            <div class="filed-placeholder">模具型号</div>
                            {{ element.moldSpec }}&nbsp;
                          </div>
                        </div>
                      </div>
                    </template>
                    <moldDispatchModule :mold-dispatch-item="element" />
                    <!-- {{ element }} -->
                  </el-popover>
                </div>
                <div v-else style="margin: 6px">
                  <div class="dispatch-item">
                    <div
                      :class="[
                        'jb-scddh',
                        element.pkDispatch ? '' : 'jb-scddh-undispatch',
                      ]"
                    >
                      {{ element.scddh }}&nbsp;
                    </div>
                    <div class="item-filed">
                      <div class="filed-name">{{ element.invname }}&nbsp;</div>
                      <div class="item-filed-content">
                        <!-- <div class="filed-placeholder">编码</div> -->
                        {{ element.invcode }}&nbsp;
                      </div>

                      <div class="item-filed-content" style="box-shadow: none">
                        <!-- <div class="filed-placeholder">规格</div> -->
                        {{ element.invtype }}&nbsp;
                      </div>
                    </div>

                    <div style="display: flex">
                      <div class="item-filed" style="flex: 1">
                        <div
                          class="item-filed-content"
                          style="box-shadow: none"
                        >
                          <div class="filed-placeholder">工序</div>
                          {{ element.opName }}&nbsp;
                        </div>
                      </div>

                      <div class="item-filed" style="flex: 1; border-left: 0px">
                        <div
                          class="item-filed-content"
                          style="box-shadow: none"
                        >
                          <div class="filed-placeholder">数量</div>
                          <div style="display: flex">
                            <div style="flex: 1">{{ element.mQty }}</div>
                            {{ element.measName }}
                          </div>
                        </div>
                      </div>
                      <div class="item-filed-content">
                        <!-- <div class="filed-placeholder">型号</div> -->
                        {{ element.invspec }}&nbsp;
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </template>
          </draggable>
        </div>
      </div>
    </div>
    <SelectMoldDialog
      ref="selectMoldDialogRef"
      @cancel-callback="cancelCallback"
      @select-mold-cavity-callback="selectMoldCavityCallback"
    />
    <CavityInvDialog
      ref="cavityInvDialogRef"
      @cancel-callback="cancelCallback"
      @mold-dispatch-callback="moldDispatchCallback"
    />
  </div>
</template>
<script setup>
  import { InfoFilled } from '@element-plus/icons-vue'
  import searchParam from './components/searchParam.vue'
  import dispatchMiddle from './components/dispatchMiddle.vue'
  import equList from './components/equList.vue'
  import _ from 'lodash'
  import draggable from 'vuedraggable'
  import {
    getKpDispatchPageApi,
    equipDispatchApi,
    getEquipDateDispatchApi,
    equipDispatchAloneApi,
    getEquipDataAloneDispatchApi,
    removeDispatchMoldApi,
    removeDispatchApi,
  } from '@/api/mes/dispatch_api'
  import { localStorageConfig } from '@/config/localstorage.config'
  import SelectMoldDialog from './dialog/SelectMoldDialog.vue'
  import CavityInvDialog from './dialog/CavityInvDialog.vue'
  import moldDispatchModule from './components/moldDispatchModule.vue'
  // const $baseLoading = inject('$baseLoading')
  const $baseMessage = inject('$baseMessage')
  const $baseConfirm = inject('$baseConfirm')
  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const dispatchMiddleRef = ref(),
    selectMoldDialogRef = ref(),
    cavityInvDialogRef = ref()
  const paginationParams = reactive({
    pageNum: 1,
    pageSize: 100,
    total: 0,
    pages: 0,
  })
  const dragInfo = reactive({
    oldIndex: -1,
    newIndex: -1,
    unDispatchItem: null,
    dispatchItem: null,
  })
  const removeDragInfo = {
    oldIndex: -1,
    newIndex: -1,
    unDispatchItem: null,
    dispatchItem: null,
  }
  const state = reactive({
    pkWc: '',
    wcItem: null,
    pkEq: '',
    eqItem: null,
    selectDate: '',
    selectTime: '',
    unDispatchList: [],
    dispatchedList: [],
    searchFormData: {},
  })
  onMounted(() => {
    queryDispatchList()
  })
  const canChangeDateTime = () => {
    if (state.dispatchedList && state.dispatchedList.length > 0) {
      if (
        state.dispatchedList.find((item) => {
          return !item.pkDispatchMid && !item.pkDispatch
        })
      ) {
        $baseMessage('保存完成之后才能切换日期!', 'error')
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  }
  const itemChildrenCount = computed(() => {
    return (item) => {
      if (item.cavityList && item.cavityList.length > 0) {
        let sum = 0
        item.cavityList.forEach((cavItem) => {
          if (cavItem.dispatchItem) {
            sum++
          }
        })
        return sum
      } else {
        return 0
      }
    }
  })
  const searchParamCallback = (searchForm) => {
    state.searchFormData = {
      pkWc: state.pkWc,
      ...(state.searchFormData || {}),
      ...(searchForm || {}),
    }
  }
  const selectEqChange = (eqItem) => {
    state.pkEq = eqItem.pkEqlist
    state.eqItem = eqItem
    getEquipDateDispatch()
  }
  const selectWcChange = (wcItem) => {
    // useMold:false
    state.pkWc = wcItem.pkWc
    state.wcItem = wcItem
    refreshData()
  }
  const saveData = async () => {
    if (!state.dispatchedList && state.dispatchedList.length === 0) {
      $baseMessage('请先选择要派工的内容', 'error')
      return
    }
    if (state.wcItem.useMold) {
      const moldDispatchParam = {
        pkCorp,
        pkEqlist: state.pkEq,
        pkWc: state.pkWc,
        pbBanci: {
          banciDate: state.selectDate,
          name: state.selectTime,
          // cavityList: state.dispatchedList,
          moldDocS: state.dispatchedList.filter((item) => {
            return !item.pkDispatchMid
          }),
        },
      }
      const { msg } = await equipDispatchApi(moldDispatchParam)
      $baseMessage(msg ? msg : '操作成功!', 'success')
      refreshData()
      getEquipDateDispatch()
    } else {
      const dispatchParam = {
        pkCorp,
        pkEqlist: state.pkEq,
        pkWc: state.pkWc,
        pbBanci: {
          banciDate: state.selectDate,
          name: state.selectTime,
          mesDispatchHList: state.dispatchedList.filter((item) => {
            if (
              !item.pkDispatch &&
              Number(item.mQty) &&
              Number(item.mQty) > 0
            ) {
              item['dispatchQty'] = item.mQty
              return true
            } else {
              return false
            }
          }),
        },
      }
      const { msg } = await equipDispatchAloneApi(dispatchParam)
      $baseMessage(msg ? msg : '操作成功!', 'success')
      refreshData()
      getEquipDateDispatch()
    }
  }
  const refreshData = () => {
    paginationParams.pageNum = 1
    queryDispatchList()
  }
  const loadData = () => {
    if (paginationParams.pageNum < paginationParams.pages) {
      paginationParams.pageNum++
      queryDispatchList()
    }
  }
  const queryDispatchList = async () => {
    if (!state.pkWc) {
      return
    }
    let params = {
      pkCorp,
      pkWc: state.pkWc,
      pageNum: paginationParams.pageNum,
      pageSize: paginationParams.pageSize,
      ...(state.searchFormData || {}),
    }
    const { data } = await getKpDispatchPageApi(params)
    data.list.forEach((item) => {
      item['mQty'] = item['dispatchQty']
    })
    paginationParams.total = data.total
    paginationParams.pages = data.pages
    if (data.pageNum > 1) {
      state.unDispatchList = state.unDispatchList.concat(data.list || [])
    } else {
      state.unDispatchList = data.list || []
    }
  }
  const showMsg = _.debounce(function (msg) {
    $baseMessage(msg, 'error')
  }, 500)
  const unmove = () => {
    if (!state.pkWc) {
      showMsg('请选择派工工作中心')
      return false
    }
    if (!state.pkEq) {
      showMsg('请先选择派工设备')
      return false
    }
    if (!state.selectDate || !state.selectTime) {
      showMsg('请先选择派工日期')
      return false
    }
  }
  const move = () => {}
  const unDispatchChange = (action) => {
    if (action.removed && action.removed.element) {
      dragInfo.unDispatchItem = action.removed.element
      dragInfo.oldIndex = action.removed.oldIndex
    } else if (action.added && action.added.element) {
      if (
        (action.added.element.pkDispatchMid ||
          action.added.element.pkDispatch) &&
        state.dispatchedList.find(
          (item) => !(item.pkDispatchMid || item.pkDispatch)
        )
      ) {
        $baseMessage('请先保存派工', 'error')
        state.unDispatchList.splice(action.added.newIndex, 1)
      } else if (
        !action.added.element.pkDispatchMid &&
        !action.added.element.pkDispatch
      ) {
        unDispatchedRemove(action.added.element, action.added.newIndex)
      } else {
        $baseConfirm(
          '是否删除',
          null,
          () => {
            dispatchedRemove(action.added.element, action.added.newIndex)
          },
          () => {
            state.unDispatchList.splice(action.added.newIndex, 1)
            setTimeout(() => {
              state.dispatchedList.splice(
                removeDragInfo.oldIndex,
                0,
                removeDragInfo.dispatchItem
              )
            }, 0)
          },
          '确认',
          '取消'
        )
      }
    }
  }
  const dispatchedChange = (action) => {
    if (action.added && action.added.element) {
      const pkInv = action.added.element.pkInv
      dragInfo.dispatchItem = action.added.element
      dragInfo.newIndex = action.added.newIndex
      if (state.wcItem.useMold) {
        selectMoldDialogRef.value.handleOpen(pkInv)
      } else {
        setTimeout(() => {
          if (
            Number(dragInfo.dispatchItem.mQty) <
            Number(dragInfo.unDispatchItem.dispatchQty)
          ) {
            const _qty =
              Number(dragInfo.unDispatchItem.dispatchQty) -
              Number(dragInfo.dispatchItem.mQty)
            const _dispatchItem = {
              ...dragInfo.unDispatchItem,
              dispatchQty: _qty,
              mQty: _qty,
            }
            state.unDispatchList.splice(dragInfo.oldIndex, 0, _dispatchItem)
          }
        }, 100)
      }
    } else if (action.removed && action.removed.element) {
      removeDragInfo.oldIndex = action.removed.oldIndex
      removeDragInfo.dispatchItem = action.removed.element
      if (
        (action.removed.element.pkDispatchMid ||
          action.removed.element.pkDispatch) &&
        state.dispatchedList.find(
          (item) => !(item.pkDispatchMid || item.pkDispatch)
        )
      ) {
        state.dispatchedList.splice(
          removeDragInfo.oldIndex,
          0,
          removeDragInfo.dispatchItem
        )
      }
    }
  }
  // 未保存的派工删除
  const unDispatchedRemove = (removeDispatchItem, newIndex) => {
    state.unDispatchList.splice(newIndex, 1)
    if (state.wcItem.useMold) {
      unDispatchRemoveMold(removeDispatchItem)
    } else {
      unDispatchRemoveNoMold(removeDispatchItem)
    }
  }
  // 未保存的模具派工删除
  const unDispatchRemoveMold = (removeDispatchItem) => {
    const cavityList = removeDispatchItem.cavityList
    cavityList.forEach((cItem) => {
      const dispatchIndex = state.unDispatchList.findIndex(
        (uItem) => cItem.dispatchItem?.pkDispatchH === uItem.pkDispatchH
      )
      if (dispatchIndex >= 0) {
        state.unDispatchList[dispatchIndex]['mQty'] =
          (Number(state.unDispatchList[dispatchIndex]['mQty']) || 0) +
          (Number(cItem.dispatchItem?.['mQty']) || 0)
      } else {
        cItem.dispatchItem &&
          state.unDispatchList.push({
            ...cItem.dispatchItem,
          })
      }
    })
  }
  // 未保存的非模具派工删除
  const unDispatchRemoveNoMold = (removeDispatchItem) => {
    const dispatchIndex = state.unDispatchList.findIndex(
      (uItem) => removeDispatchItem.pkDispatchH === uItem.pkDispatchH
    )
    if (dispatchIndex >= 0) {
      state.unDispatchList[dispatchIndex]['mQty'] =
        (Number(state.unDispatchList[dispatchIndex]['mQty']) || 0) +
        (Number(removeDispatchItem?.['mQty']) || 0)
    } else {
      removeDispatchItem &&
        state.unDispatchList.push({
          ...removeDispatchItem,
        })
    }
  }
  // 已经保存的派工删除
  const dispatchedRemove = async (removeDispatchItem, newIndex) => {
    state.unDispatchList.splice(newIndex, 1)
    let res = {}
    if (state.wcItem.useMold) {
      res = await removeDispatchMoldApi({
        pkDispatchMid: removeDispatchItem.pkDispatchMid,
      })
    } else {
      res = await removeDispatchApi({
        pkDispatch: removeDispatchItem.pkDispatch,
      })
    }
    $baseMessage(res.msg ? res.msg : '删除成功', 'success')
    refreshData()
    getEquipDateDispatch()
  }

  const selectMoldCavityCallback = (moldCavityItem) => {
    // 根据模型查询型腔
    // moldCavityItem.pkCavity
    cavityInvDialogRef.value.handleOpen(moldCavityItem, dragInfo.dispatchItem)
  }
  const selectDateTimeCallback = (d, t) => {
    state.selectDate = d
    state.selectTime = t
    getEquipDateDispatch()
  }
  const getEquipDateDispatch = async () => {
    if (!state.pkEq || !state.pkWc || !state.selectDate || !state.selectTime) {
      return
    }
    const params = {
      banciName: state.selectTime,
      banciDate: state.selectDate,
      pkEqlist: state.pkEq,
    }
    let data
    if (state.wcItem.useMold) {
      const { data: d } = await getEquipDateDispatchApi(params)
      data = d
    } else {
      const { data: d } = await getEquipDataAloneDispatchApi(params)
      data = d.map((item) => {
        return {
          ...item,
          mQty: item.dispatchQty || 0,
        }
      })
    }
    state.dispatchedList = _.clone(data)
  }
  const cancelCallback = () => {
    state.dispatchedList.splice(dragInfo.newIndex, 1)
    state.unDispatchList.splice(dragInfo.oldIndex, 0, dragInfo.unDispatchItem)
  }
  const moldDispatchCallback = (moldCavityItem, cavityList) => {
    const _moldCavityItem = _.clone(moldCavityItem)
    const _cavityList = _.clone(cavityList)
    _cavityList.forEach((item) => {
      if (item.dispatchItem && item.dispatchItem.mQty) {
        if (
          item.dispatchItem.pkDispatchH === dragInfo.unDispatchItem.pkDispatchH
        ) {
          if (
            Number(item.dispatchItem.mQty) <
            Number(dragInfo.unDispatchItem.dispatchQty)
          ) {
            const _qty =
              Number(dragInfo.unDispatchItem.dispatchQty) -
              Number(item.dispatchItem.mQty)
            const _dispatchItem = {
              ...dragInfo.unDispatchItem,
              dispatchQty: _qty,
              mQty: _qty,
            }
            state.unDispatchList.splice(dragInfo.oldIndex, 0, _dispatchItem)
          }
        } else {
          const sdIndex = state.unDispatchList.findIndex((uItem) => {
            return item.dispatchItem.pkDispatchH === uItem.pkDispatchH
          })
          // Number(item.dispatchItem.mQty) =
          if (sdIndex >= 0) {
            let _qty =
              Number(state.unDispatchList[sdIndex].mQty) -
              Number(item.dispatchItem.mQty)
            state.unDispatchList[sdIndex]['mQty'] = _qty
          }
        }
        item.dispatchItem['dispatchQty'] = item.dispatchItem.mQty
      }
    })
    const mItem = {
      ...(_moldCavityItem || {}),
      cavityList: _cavityList,
    }
    state.dispatchedList.splice(dragInfo.newIndex, 1, mItem)
  }
</script>
<style lang="scss" scoped>
  .dispatch-equ-sort-container {
    position: relative;
    .content-root {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      display: flex;
      flex-direction: row;
      .info-content {
        position: relative;
        display: flex;
        flex: 1;
        flex-direction: column;
        .info-content-top {
          position: absolute;
          top: 6px;
          right: 0;
          bottom: 260px;
          left: 0;
          background-color: #f6f8ff;
          .drag-content {
            height: calc(100% - 44px);
            overflow: scroll;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            .list-group {
              position: relative;
              display: flex;
              flex-wrap: wrap;
              width: 100%;
              min-height: 200px;
            }
          }
        }
        .info-content-bottom {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 220px;
          overflow: scroll;
          background-color: #f0f1f2;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          .list-group {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            width: 100%;
            min-height: 200px;
          }
        }
      }

      .dispatch-item {
        position: relative;
        padding: 3px;
        background: linear-gradient(
          180deg,
          #ecf2ff 0%,
          rgba(255, 255, 255, 0.1) 60%
        );
        border: 2px solid #ffffff;
        border-radius: 3px;
        box-shadow: 0 4px 16px rgba(55, 99, 170, 0.1);
        transition: box-shadow 0.3s ease-in-out;
        &:hover {
          box-shadow: 0 4px 16px rgba(55, 99, 170, 0.2);
        }
        &:hover::before {
          position: absolute;
          top: -2px;
          left: -2px;
          z-index: 0;
          width: calc(100% + 4px);
          height: calc(100% + 4px);
          content: '';
          border: 1px solid #0052d9;
        }
        .jb-scddh {
          position: relative;
          width: 100%;
          height: 16px;
          padding-left: 6px;
          margin-bottom: 3px;
          font-size: 12px;
          font-weight: bold;
          line-height: 16px;
          color: white;
          text-align: left;
          background: linear-gradient(45deg, #4793ff, #0064e4);
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        }

        .opt-tag {
          position: absolute;
          top: 3px;
          right: 5px;
          font-size: 10px;
          font-weight: bold;
          line-height: 16px;
          color: #ffffff;
        }

        .jb-scddh-undispatch {
          background: linear-gradient(45deg, #d2aa74, #f0c68e);
        }
        .jb-scddh-fangong {
          background: linear-gradient(45deg, #e14a8c, #d23bd0);
        }

        .item-filed {
          padding: 0px 6px;
          margin-bottom: 3px;
          border: 1px solid rgb(235, 236, 236);
          .filed-name {
            font-size: 14px;
            font-weight: 600;
            line-height: 16px;
            color: #333;
          }
          .filed-placeholder {
            font-size: 10px;
            font-weight: 400;
            line-height: 14px;
            color: #999;
          }
          .item-filed-content {
            margin-bottom: 3px;
            font-size: 12px;
            font-weight: 500;
            line-height: 16px;
            color: #777;
            box-shadow: 0 1px 0 0 #ebecec;
          }
        }
        .filed-number {
          padding-left: 6px;
          font-size: 10px;
          font-weight: 400;
          line-height: 14px;
          line-height: 16px;
          color: #999;
        }
        :deep(.el-input__wrapper) {
          padding: 0;
          background-color: transparent;
          // border-bottom: 1px solid #ffffff;
          border: 1px solid #f0f1f2;
          border-radius: 0;
          box-shadow: none;
        }
        :deep(.el-input__inner) {
          font-weight: 600px;
          color: #333;
        }
        :deep(.el-tag) {
          height: 16px;
          padding: 0 3px;
        }
        .dispatch-item-filed {
          display: flex;
          flex-direction: row;
          align-items: center;
        }
        .dispatch-item-value {
          flex: 1;
          padding: 0 6px;
        }
      }
    }
  }
</style>
